package jjn.round1;

/**
 * @author Jjn
 * @since 2022/9/4 23:36
 */
public class LeetCode14_LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            prefix = getLongerCommonPrefixBetweenTwo(strs[i], prefix);
        }
        return prefix;
    }

    private String getLongerCommonPrefixBetweenTwo(String s1, String s2) {
        if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
            return "";
        }
        int max = Math.min(s1.length(), s2.length());
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < max; i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                break;
            }
            stringBuilder.append(s1.charAt(i));
        }
        return stringBuilder.toString();
    }
}
